package com.tjetc.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tjetc.common.Result;
import com.tjetc.domain.Admin;
import com.tjetc.domain.Role;
import com.tjetc.service.AdminService;
import com.tjetc.service.impl.AdminServiceImpl;
import com.tjetc.utils.JwtUtil;
import com.tjetc.utils.PageInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.UUID;

@WebServlet("/admin/*")
@MultipartConfig(location = "D:\\yiyuanphoto")
public class AdminServlet extends HttpServlet {
    private AdminService adminService = new AdminServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        try {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        int rid= Integer.parseInt(request.getParameter("role_id"));
        Admin admin = adminService.login(username,password,rid);
        String token= JwtUtil.createToken(username);
       /* System.out.println(admin);*/
        if (admin==null){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("用户名/密码错误"));
        }
        else{
           /* Admin admin1=adminService.login()*/
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success(token,"登录成功"));
        }

    }


    protected void checkToken(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token=req.getHeader("token");
        boolean b=JwtUtil.isValid(token);
        if (b){
            resp.getWriter().print(b);
        }
    }

    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("username");
        String phone = request.getParameter("phone");
        String curPage = request.getParameter("curPage");
        String ps = request.getParameter("pageSize");
        name=name==null?"":name;
        phone=phone==null?"":phone;
        //接受请求参数
        //空处理:赋值给当前页码
        int currentPage = curPage == null ? 1:Integer.valueOf(curPage);
        //每页显示的条数
        int pageSize = ps == null ? 5 : Integer.parseInt(ps);
        //总记录数
        int count = adminService.getCount(name,phone);
        PageInfo<Admin> pageInfo = new PageInfo<>(currentPage, count, pageSize);
        List<Admin> list = adminService.list(name,phone,pageInfo);
        pageInfo.setList(list);
        new ObjectMapper().writeValue(response.getOutputStream(),pageInfo);
    }

    protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        Integer age = Integer.valueOf(request.getParameter("age"));
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String sex = request.getParameter("sex");
        Integer rid = Integer.valueOf(request.getParameter("rid"));
        Integer status = Integer.valueOf(request.getParameter("status"));
        Part part = request.getPart("photo");
        Admin admin = new Admin();
        admin.setUsername(username);
        admin.setAge(age);
        admin.setPhone(phone);
        admin.setEmail(email);
        admin.setSex(sex);
        admin.setStatus(status);
        Role role = new Role();
        role.setId(rid);
        admin.setRole(role);
        if (part!=null && part.getSize()>0){
            String fn = part.getSubmittedFileName();
            String extName = fn.substring(fn.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString()+extName;
            part.write(fileName);
            admin.setAvatar("upload/"+fileName);
        }
        boolean b = adminService.add(admin);
        if (b){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success("添加成功"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("添加失败，出异常喽！"));
    }

    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id = Integer.valueOf(request.getParameter("id"));
        Admin oldAdmin = adminService.getById(id);
        String username = request.getParameter("username");
        Integer age = Integer.valueOf(request.getParameter("age"));
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String sex = request.getParameter("sex");
        Integer status = Integer.valueOf(request.getParameter("status"));
        Part part = request.getPart("photo");
        Admin admin = new Admin();
        admin.setId(id);
        admin.setUsername(username);
        admin.setAge(age);
        admin.setPhone(phone);
        admin.setEmail(email);
        admin.setSex(sex);
        admin.setStatus(status);
        if (part!=null && part.getSize()>0 && part.getSubmittedFileName()!=null){
            String fn = part.getSubmittedFileName();
            String extName = fn.substring(fn.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString()+extName;
            part.write(fileName);
            admin.setAvatar("upload/"+fileName);
        }else{
            admin.setAvatar(oldAdmin.getAvatar());
        }
        boolean b = adminService.update(admin);
        if (b){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success("修改成功"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("修改失败"));
    }

    protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id = Integer.valueOf(request.getParameter("id"));
        Integer status = Integer.valueOf(request.getParameter("status"));
        boolean b = adminService.updateStatus(status,id);
        if (b){
            if (status==0){
                new ObjectMapper().writeValue(response.getOutputStream(), Result.success("停用成功"));
            }else if(status==1){
                new ObjectMapper().writeValue(response.getOutputStream(), Result.success("启用成功"));
            }
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("停用失败"));
    }


    protected void findPasswordById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        Admin admin=adminService.getpwdById(id);
        String password=admin.getPassword();
        new ObjectMapper().writeValue(response.getOutputStream(),password);
    }


    protected void updatepwd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        String password=request.getParameter("newPassword");
        Admin admin=new Admin();
        admin.setId(id);
        admin.setPassword(password);
        boolean b=adminService.updatepwd(admin);
        if (b){
            new ObjectMapper().writeValue(response.getOutputStream(), Result.success("修改成功"));
        }
        new ObjectMapper().writeValue(response.getOutputStream(), Result.fail("修改失败"));
    }
    protected void info(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        Admin admin=adminService.findByName(username);
        new ObjectMapper().writeValue(response.getOutputStream(), Result.success(admin));
    }
}
